package cn.hfatec.shms.system.organization.service;

import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.enums.KeyTypeEnum;
import cn.hfatec.shms.exception.KeyGenException;
import cn.hfatec.shms.system.organization.dao.OrganizationDao;
import cn.hfatec.shms.system.organization.model.Organization;
import cn.hfatec.shms.system.organization.model.OrganizationParams;
import cn.hfatec.shms.system.organization.model.OrganizationView;
import cn.hfatec.shms.system.user.dao.UserDao;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.utils.KeyGenUtils;
import com.google.common.collect.Lists;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("OrganizationService")
public class OrganizationService {

    public static final String BEAN_ID = "OrganizationService";

    //注入Dao层
    @Resource(name = "OrganizationDao")
    private OrganizationDao organizationDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    //注入UserDao
    @Resource(name = "UserDao")
    private UserDao userDao;

    /**
     * 查询数据
     *
     * @param organizationParams
     */
    @Transactional
    @MysqlDataSource
    public List queryOrganizationTable(OrganizationParams organizationParams) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", organizationParams);
        return baseDao.queryList("queryOrganization", params);
    }

    /**
     * 插入数据
     *
     * @param organization
     */
    @Transactional
    @MysqlDataSource
    public void saveOrganization(Organization organization) throws KeyGenException {
        if (organization.getId() != null) {
            Organization result = getOrganization(organization.getId());
            if (result != null) {
                organizationDao.update(organization);
            } else {
                organization.setOrgId(KeyGenUtils.createKeyByType(KeyTypeEnum.ORG_KEY));
                Organization organization1 = organizationDao.getOrganizationByOrgId(organization.getParentOrgId());
                organization.setOrgLevelCode(organization1.getOrgLevelCode() + "|" + organization.getOrgId());
                organizationDao.insert(organization);
            }
        } else {
            organization.setOrgId(KeyGenUtils.createKeyByType(KeyTypeEnum.ORG_KEY));
            Organization organization1 = organizationDao.getOrganizationByOrgId(organization.getParentOrgId());
            organization.setOrgLevelCode(organization1.getOrgLevelCode() + "|" + organization.getOrgId());
            organizationDao.insert(organization);
        }
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    @MysqlDataSource
    public void deleteOrganization(Integer id, String orgId) {

        userDao.updateUserOrgIdforOrgId(orgId);
        organizationDao.delete(id);
    }


    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    @MysqlDataSource
    public Organization getOrganization(Integer id) {

        return organizationDao.getOrganizationById(id);
    }

    /**
     * 根据ID获取数据
     *
     * @param orgId
     */
    @Transactional
    public Organization getOrganization(String orgId) {

        return organizationDao.getOrganizationByOrgId(orgId);
    }

    /**
     * 查询所有的机构
     *
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @Transactional
    @MysqlDataSource
    public List<OrganizationView> queryAllOrgList() throws InvocationTargetException, IllegalAccessException {
        //查询所有已分配的机构信息
        OrganizationParams organizationParams = new OrganizationParams();
        List<Organization> allOrgList = organizationDao.queryOrganization(organizationParams);
        return getOrgList(ShmsConstant.ORG_CACHE, allOrgList);
    }

    /**
     * 根据父节点ID、总菜单数据，递归获取机构视图信息
     *
     * @param parentOrgId
     * @param allOrgList
     * @return
     * @throws java.lang.reflect.InvocationTargetException
     * @throws IllegalAccessException
     */
    @Transactional
    @MysqlDataSource
    public List<OrganizationView> getOrgList(String parentOrgId, List<Organization> allOrgList) throws InvocationTargetException, IllegalAccessException {
        List<OrganizationView> list = Lists.newArrayList();
        for (Organization org : allOrgList) {
            if (org.getParentOrgId() != null && org.getParentOrgId().equals(parentOrgId)) {
                OrganizationView orgView = new OrganizationView();
                BeanUtils.copyProperties(orgView, org);
                orgView.setChildrenOrgList(getOrgList(orgView.getOrgId(), allOrgList));
                list.add(orgView);
            }
        }
        return list;
    }

    /**
     * 根据机构ID、总菜单数据，递归获取所有的子菜单机构ID(逗号分隔)
     *
     * @param orgId
     * @param allOrgList
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @Transactional
    @MysqlDataSource
    public String getOrgIdList(String orgId, List<Organization> allOrgList) throws InvocationTargetException, IllegalAccessException {
        String str = "";

        for (Organization org : allOrgList) {
            if (org.getParentOrgId() != null && org.getParentOrgId().equals(orgId)) {
                str += org.getOrgId() + ",";
                str += getOrgIdList(org.getOrgId(), allOrgList);
            }
        }
        return str;
    }

    /**
     * 获取当前机构及子机构的集合
     *
     * @param user
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @Transactional
    @MysqlDataSource
    public List<String> getAssignOrgIdList(User user) throws InvocationTargetException, IllegalAccessException {
        List<String> list = new ArrayList();
        OrganizationParams organizationParams = new OrganizationParams();
        List<Organization> allOrgList = this.queryOrganizationTable(organizationParams);
        List<OrganizationView> orgList = this.getOrgList(user.getOrgId(), allOrgList);
        String assignOrgId = user.getOrgId() + "," + this.getOrgIdList(user.getOrgId(), allOrgList);
        assignOrgId = assignOrgId.substring(0, assignOrgId.length() - 1);
        String[] assignArray = assignOrgId.split(",");
        for (int i = 0; i < assignArray.length; i++) {
            list.add(assignArray[i]);
        }
        return list;
    }

    /**
     * 根据父节点ID、总机构数据，递归获取机构视图信息
     *
     * @param orgId
     * @return
     * @throws java.lang.reflect.InvocationTargetException
     * @throws IllegalAccessException
     */
    @Transactional
    @MysqlDataSource
    public List getOrgIdList(String orgId) throws InvocationTargetException, IllegalAccessException {
        List list = Lists.newArrayList();
        list.add(orgId);
        OrganizationParams organizationParams = new OrganizationParams();
        List<Organization> allOrgList = this.queryOrganizationTable(organizationParams);
        for (Organization org : allOrgList) {
            if (org.getParentOrgId() != null && org.getParentOrgId().equals(orgId)) {
                OrganizationView orgView = new OrganizationView();
                BeanUtils.copyProperties(orgView, org);
                orgView.setChildrenOrgList(getOrgIdList(orgView.getOrgId()));
                list.add(orgView.getOrgId());
            }
        }
        return list;
    }

    /**
     * 根据用户所以在的机构ID获取属于医院的机构或上级机构数据
     *
     * @param orgId
     */
    @Transactional
    @MysqlDataSource
    public Organization getOrg(String orgId) {
        Organization organization = organizationDao.getOrganizationByOrgId(orgId);
        //如果是医院
        if (organization.getIsHospital() == ShmsConstant.IS_HOSPITAL_YES) {
            return organization;
        } else {//不是医院查找上级单位是否是医院
            int isHospital = 0;
            if (organization.getIsHospital() != null) {
                isHospital = organization.getIsHospital();
            }
            String orgIds = organization.getParentOrgId();
            while (isHospital == ShmsConstant.IS_HOSPITAL_NO) {
                organization = organizationDao.getOrganizationByOrgId(orgIds);
                //都找不到是医院的机构则返回原机构
                if (organization == null) {
                    return organizationDao.getOrganizationByOrgId(orgId);
                }
                if(organization.getIsHospital() == null){
                    return organizationDao.getOrganizationByOrgId(orgId);
                }
                //该机构不是医院机构就继续找上级机构，如果是就返回本机构
                if (organization.getIsHospital() == ShmsConstant.IS_HOSPITAL_NO) {
                    isHospital = organization.getIsHospital();
                    orgIds = organization.getParentOrgId();
                } else {
                    return organization;
                }
            }
            return organization;
        }
    }

    /**
     * 根据机构Id获取数据
     * @param orgId
     * @return
     */
    @Transactional
    @MysqlDataSource
    public Organization getOrganizationByOrgId(String orgId){
        return organizationDao.getOrganizationByOrgId(orgId);
    }
}